<template>
  <el-container class="app-container">
    <!-- 左侧导航栏 -->
    <el-aside width="200px" class="sidebar">
      <div class="nav-title">配送员后台</div>
      <el-menu :default-active="currentPage" class="el-menu-vertical-demo">
        <el-menu-item index="viewOrders" @click="switchPage('viewOrders')">
          <i class="el-icon-s-order"></i> 查看订单
        </el-menu-item>
      </el-menu>
    </el-aside>

    <!-- 主内容区域 -->
    <el-container>
      <el-main>
        <!-- 查看订单页面 -->
        <div v-if="currentPage === 'viewOrders'">
          <!-- 订单筛选 -->
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span>订单筛选</span>
            </div>
            <el-row class="filter-row">
              <el-button
                type="primary"
                plain
                @click="filterOrders('all')"
                class="filter-btn"
                :class="{ active: selectedTab === 'all' }"
              >
                全部订单
              </el-button>
              <el-button
                type="success"
                plain
                @click="filterOrders('new')"
                class="filter-btn"
                :class="{ active: selectedTab === 'new' }"
              >
                新订单
              </el-button>
              <el-button
                type="warning"
                plain
                @click="filterOrders('in-progress')"
                class="filter-btn"
                :class="{ active: selectedTab === 'in-progress' }"
              >
                正在进行的订单
              </el-button>
              <el-button
                type="info"
                plain
                @click="filterOrders('history')"
                class="filter-btn"
                :class="{ active: selectedTab === 'history' }"
              >
                历史订单
              </el-button>
            </el-row>
          </el-card>

          <!-- 订单列表 -->
          <el-card class="box-card table-card">
            <div slot="header" class="clearfix">
              <span>订单列表</span>
            </div>
            <el-table
              :data="paginatedOrders"
              border
              style="width: 100%; margin-top: 20px"
            >
              <el-table-column prop="code" label="订单编号" width="200" />
              <el-table-column prop="deliveryAddress" label="收货地址" width="150" />
              <el-table-column prop="username" label="收货人" width="120" />
              <el-table-column prop="products" label="商品信息" width="200">
                <template slot-scope="scope">
                  {{ formatProducts(scope.row.products || '无商品信息') }}
                </template>
              </el-table-column>
              <el-table-column prop="storeName" label="商店名称" width="150" />
              <el-table-column prop="orderTime" label="创建时间" width="180" />
              <el-table-column prop="status" label="订单状态" width="100">
                <template slot-scope="scope">
                  {{ getOrderStatus(scope.row.operationType) }}
                </template>
              </el-table-column>

              <el-table-column label="操作" width="150">
                <template slot-scope="scope">
                  <el-button
                    v-if="scope.row.operationType === 3"
                    type="primary"
                    size="small"
                    @click="acceptOrder(scope.row)"
                  >
                    接单
                  </el-button>
                  <el-button
                    v-else-if="scope.row.operationType === 4"
                    type="success"
                    size="small"
                    @click="completeOrder(scope.row)"
                  >
                    完成订单
                  </el-button>
                  <el-button
                    v-else-if="scope.row.operationType === 5"
                    type="info"
                    size="small"
                    disabled
                  >
                    已完成
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <!-- 分页 -->
            <el-pagination
              background
              layout="prev, pager, next"
              :page-size="pageSize"
              :current-page="currentPageIndex"
              :total="filteredOrders.length"
              @current-change="handlePageChange"
              style="margin-top: 20px"
            />
          </el-card>
        </div>
      </el-main>
    </el-container>
  </el-container>
</template>

<script>
export default {
  name: "DelivererView",
  data() {
    return {
      currentPage: "viewOrders",
      selectedTab: "all",
      userId: null,
      orders: [],
      pageSize: 5,
      currentPageIndex: 1,
    };
  },
  created() {
    this.userId = this.$route.query.id;
    if (!this.userId) {
      console.error("用户 ID 不存在，无法加载页面数据！");
      this.$message.error('缺少用户信息，无法加载数据！');
      return;
    }
    this.fetchAndFilterOrders("all");
  },
  computed: {
    filteredOrders() {
      switch (this.selectedTab) {
        case "new":
          return this.orders.filter(o => o.operationType === 3);
        case "in-progress":
          return this.orders.filter(o => o.operationType === 4);
        case "history":
          return this.orders.filter(o => o.operationType === 5);
        default:
          return this.orders;
      }
    },
    paginatedOrders() {
      const start = (this.currentPageIndex - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.filteredOrders.slice(start, end);
    }
  },
  methods: {
    switchPage(page) {
      this.currentPage = page;
    },
    async fetchAndFilterOrders(tab) {
      try {
        const response = await this.$axios.get('/getDeliveryorder', {
          params: { 
            type: tab,
            userId: this.userId
          },
        });

        if (response.data?.code === "200") {
          this.orders = this.parseOrders(response.data.data || []);
          this.selectedTab = tab;
          this.currentPageIndex = 1;
          this.$message.success('订单数据加载成功！');
        } else {
          throw new Error(response.data?.msg || '获取订单数据失败');
        }
      } catch (error) {
        console.error("获取订单数据失败:", error);
        this.$message.error(error.message || '服务器错误，无法获取订单数据');
      }
    },
    parseOrders(ordersData) {
      return ordersData
        .map(order => {
          try {
            // 检查必要字段是否存在
            if (!order.id || !order.code || !order.operationType) {
              console.warn(`订单缺少必要字段：`, order);
              return null;
            }

            let content;
            try {
              content = typeof order.content === 'string' 
                ? JSON.parse(order.content) 
                : (order.content || {});
            } catch (e) {
              console.warn(`订单内容解析失败：${order.content}`);
              return null;
            }

            // 验证content中的必要字段
            if (!content.username || !content.deliveryAddress || !content.orderTime) {
              console.warn(`订单内容缺少必要信息：`, content);
              return null;
            }

            // 验证operationType是否为有效值
            if (![3, 4, 5].includes(order.operationType)) {
              console.warn(`无效的订单状态：${order.operationType}`);
              return null;
            }

            return {
              id: order.id,
              code: order.code,
              username: content.username,
              storeName: content.storeName || '未知',
              products: content.products || '无商品信息',
              deliveryAddress: content.deliveryAddress,
              orderTime: content.orderTime,
              operationType: order.operationType,
            };
          } catch (e) {
            console.warn(`订单处理失败：`, e);
            return null;
          }
        })
        .filter(Boolean); // 过滤掉所有null值
    },
    formatProducts(products) {
      if (typeof products === 'string') {
        return products;
      }
      if (Array.isArray(products)) {
        return products.map(p => p.name).join(', ');
      }
      return '暂无商品信息';
    },
    getOrderStatus(operationType) {
      const statusMap = {
        3: '新订单',
        4: '配送中',
        5: '已完成'
      };
      return statusMap[operationType] || '未知状态';
    },
    filterOrders(tab) {
      this.selectedTab = tab;
      this.fetchAndFilterOrders(tab);
    },
    handlePageChange(page) {
      this.currentPageIndex = page;
    },
    async acceptOrder(order) {
      try {
        const response = await this.$axios.post('/deliveryAcceptOrder', { 
          orderId: order.code,
          userId: this.userId
        });
        
        if (response.data?.code === "200") {
          await this.fetchAndFilterOrders(this.selectedTab);
          this.$message.success('接单成功！');
        } else {
          throw new Error(response.data?.msg || '接单失败');
        }
      } catch (error) {
        console.error("接单失败:", error);
        this.$message.error(error.message || '接单失败，请重试');
      }
    },
    async completeOrder(order) {
      try {
        const response = await this.$axios.post('/deliveryOKOrder', { 
          orderId: order.code,
          userid: this.userId
        });
        
        if (response.data?.code === "200") {
          await this.fetchAndFilterOrders(this.selectedTab);
          this.$message.success('订单已完成！');
        } else {
          throw new Error(response.data?.msg || '完成订单失败');
        }
      } catch (error) {
        console.error("完成订单失败:", error);
        this.$message.error(error.message || '完成订单失败，请重试');
      }
    }
  }
};
</script>

<style scoped>
.app-container {
  height: 100vh;
}

.sidebar {
  background-color: #304156;
  color: white;
}

.nav-title {
  padding: 20px;
  font-size: 18px;
  text-align: center;
}

.box-card {
  margin-bottom: 20px;
}

.filter-row {
  display: flex;
  gap: 10px;
}

.filter-btn.active {
  border-color: #409EFF;
  color: #409EFF;
}

.table-card {
  margin-top: 20px;
}
</style>